<template>
	<view>
		<view class="home-item">
			<text>账号</text>
			<input type="text" v-model="formData.username">
		</view>
		<view class="home-item">
			<text>密码</text>
			<input type="text" v-model="formData.password">
		</view>
		<button @click="login" size="mini">登录</button>
		<button @click="register" size="mini">注册</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					username: '',
					password: ''
				}
			}
		},
		onLoad() {},
		methods: {
			login() {
				let formData = {
					...this.formData
				}
				this.$api.login(formData).then(res => {
					uni.showToast({
						title: '登录成功'
					});
					const {
						userInfo,
						token,
						tokenExpired
					} = res
					uni.setStorageSync('uni_id_token', token)
					uni.setStorageSync('uni_id_token_expired', tokenExpired)
					this.$t.dbSet('userinfo',userInfo)
					uni.reLaunch({
						url: '/pages/index/index'
					});
					uni.$emit('update:editor')
				}).catch(err => {
					console.log(err);
					uni.showModal({
						content: JSON.stringify(err.message),
						showCancel: false
					})
				})
			},
			
			register() {
				let formData = {
					...this.formData
				}
				this.$api.register(formData).then(res => {
					uni.showToast({
						title: '注册成功'
					});
					uni.setStorageSync('uni_id_token', res.token)
					uni.setStorageSync('uni_id_token_expired', res.tokenExpired)
				}).catch(err => {
					uni.showModal({
						content: JSON.stringify(err),
						showCancel: false
					})
				})
			},

		}
	}
</script>

<style lang="scss">
	.home-item {
		display: flex;

		input {
			border: 1px red solid;
		}
	}
</style>
